<template>
  <div class="boxs">
    <div class="flex-box">
      <div>
         <el-input
              v-model="queryParams.query"
              placeholder="请输入订单名称"
              clearable
              style="width:160px;margin-right:10px"
              @input="handleQuery"
          />
      </div>
      <div>
        <el-select v-model="queryParams.stateQuery" placeholder="请选择状态" style="width:140px;margin-right:10px">
          <el-option
            v-for="item in stateoptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div>
        <el-select v-model="queryParams.customerId" placeholder="请选择客户" style="width:140px;margin-right:10px">
            <el-option
              v-for="item in customers"
              :key="item.id"
              :label="item.username"
              :value="item.id">
            </el-option>
          </el-select>
      </div>
      <div>
        <el-select v-model="queryParams.workerId"  placeholder="请选择工人"  style="width:140px;margin-right:10px">
                        <el-option
                          v-for="item in workers"
                          :key="item.id"
                          :label="item.username"
                          :value="item.id">
                        </el-option>
                      </el-select>
      </div>
      <div>
        <el-date-picker
          v-model="queryParams.dataArry"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="handleDateChange"
          style="width:280px;margin-right:10px"
          >
        </el-date-picker>
      </div>
      <div>
        <el-button    size="small"  @click="reset()">重置</el-button>
        <el-button icon="el-icon-download" type="primary"  size="small"  @click="doExport()">导出</el-button>
      </div>
    </div>
    <el-table :data="OrderArr" style="width: 100%" v-loading="loading">
      <!-- <el-table-column label="订单编号" align="center" prop="id" min-width="80">
        <template slot-scope="scope">
          {{ scope.row.orderId}}
        </template> 
      </el-table-column> -->
      <el-table-column label="创建时间" align="center" prop="createTime" min-width="100">
        <template slot-scope="scope">
          {{formatterCreateTime(scope.row.createTime)}}
        </template>
      </el-table-column>
      <el-table-column label="工人" align="center" prop="name" min-width="100">
        <template slot-scope="scope">
          {{scope.row.workerName}}
        </template>
      </el-table-column>
      <el-table-column label="计划工作量" align="center" prop="number" min-width="100">
        <template slot-scope="scope">
          {{scope.row.number}}
        </template>
      </el-table-column>
      <el-table-column label="实际工作量" align="center" prop="real_number" min-width="100">
        <template slot-scope="scope">
          {{scope.row.real_number}}
        </template>
      </el-table-column>
      <el-table-column label="单位" align="center" prop="unitName" min-width="60">
        <template slot-scope="scope">
          {{scope.row.unitName}}
        </template>
      </el-table-column>
      <el-table-column label="单价(元)" align="center" prop="workerprice" min-width="100">
        <template slot-scope="scope">
          {{scope.row.workerprice}}
        </template>
      </el-table-column>
      <el-table-column label="实际收益(元)" align="center" prop="actualIncome" min-width="100">
        <template slot-scope="scope">
          {{scope.row.actualIncome}}
        </template>
      </el-table-column>
      <el-table-column label="客户单价(元)" align="center" prop="customerprice" min-width="100">
        <template slot-scope="scope">
          {{scope.row.customerprice}}
        </template>
      </el-table-column>
      <el-table-column label="订单收入(元)" align="center" prop="customerOutcome" min-width="100">
        <template slot-scope="scope">
          {{scope.row.customerOutcome}}
        </template>
      </el-table-column>
      <el-table-column label="工序" align="center" prop="processName" min-width="100">
        <template slot-scope="scope">
          {{scope.row.processName}}
        </template>
      </el-table-column>
      <el-table-column label="订单" align="center" prop="name" min-width="100">
        <template slot-scope="scope">
          {{scope.row.orderName}}
        </template>
      </el-table-column>
      <el-table-column label="客户" align="center" prop="customerName" min-width="100">
        <template slot-scope="scope">
          {{scope.row.customerName}}
        </template>
      </el-table-column>
       <el-table-column label="状态" align="center" prop="state" min-width="100">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.orderState==1?'':scope.row.orderState==2?'success':scope.row.orderState==3?'warning':scope.row.orderState==4?'danger':'info'"
            effect="dark">
            {{ scope.row.orderState==1?'进行中':scope.row.orderState==2?'已完成':scope.row.orderState==3?'已回款':scope.row.orderState==4?'已发工资':'-'}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="完成时间" align="center" prop="finishTime" min-width="130">
        <template slot-scope="scope">
          {{scope.row.finishTime}}
        </template>
      </el-table-column>
    </el-table>
    <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.size"
        @pagination="getFinance"
    />
  </div>
</template>
<script>
import {getCustomer,getProcesses,getWorker,getFinance,getFinanceNoLimit} from '@/api/admin';
import {formatDate} from "@/utils";
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver'
export default {
  name:"Finance",
  data () {
    return {
      
      stateoptions:[
        {
          label:'进行中',
          value:1,
        },
        {
           label:'已完成',
          value:2,
        },
        {
           label:'已回款',
          value:3,
        },
        {
           label:'已发工资',
          value:4,
        }
      ],
      queryParams:{
        page:1,
        size:10,
        stateQuery:'',
      },
      customers:[],
      processes:[],
      units:[],
      workers:[],
      total:0,
      loading:false,
      addLoading:false,
      OrderArr: [],
      dialogVisible: false,
      rolesArr: [],
      moreArr: [],
      search: '',
    }
  },
  async created () {
    this.getFinance()
    this.getCustomer();
      this.getWorker();
      this.getProcesses();
  },
  watch: {
    'queryParams.stateQuery'(value) {
      this.handleQuery()
    },
    'queryParams.customerId'(value) {
      this.handleQuery()
    },
    'queryParams.workerId'(value) {
      this.handleQuery()
    }
  },
  methods: {
    //获取工人列表
    async getCustomer(){
      const {data,total} = await getCustomer();
      this.customers=data;
    },
    async getProcesses(){
      const {data,total} = await getProcesses();
      this.processes=data;
    },
    async getWorker(){
      const {data,total} = await getWorker();
      this.workers=data;
    },
    formatterCreateTime(time){
      return formatDate(time);
    },
    async getFinance () {
      this.loading=true;
      const {data,total} = await getFinance(this.queryParams);
      this.loading=false;
      this.OrderArr = data;
      this.total=total;
    },
    handleDateChange(value) {
      console.log('选中的日期:', value); // 可以是日期字符串或null（如果未选择日期）
      this.queryParams.startDate=value[0]+' 00:00:00'
      this.queryParams.endDate=value[1]+' 00:00:00'
     this.handleQuery()
    },
    handleQuery(){
      this.queryParams.page=1;
      this.getFinance();
    },
    reset(){
      this.queryParams={
        page:1,
        size:10,
        stateQuery:'',
      }
      this.handleQuery()
    },
    async doExport() {
	  // 开始生成文件时，添加一个loading让它一直转，待生成excel完毕之后再关掉
      this.loading = true
      // 关键函数
      function exportToExcel(fileName, tableData) {
        const worksheet = XLSX.utils.json_to_sheet(tableData)
        const workbook = { Sheets: { data: worksheet }, SheetNames: ['data'] }
        const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
        const data = new Blob([excelBuffer], { type: 'application/octet-stream' })
        saveAs(data, `${fileName}.xlsx`)
      }
      // fileName 为生成的 Excel 文件名称，为避免重复，这里使用时间戳作为前缀
      const moment = require('moment');
      const fileName = moment().format('YYYY-MM-DD hh:mm:ss') + '收益数据'
      const excelData = []
      let res=await getFinanceNoLimit(this.queryParams);
      let data=res.data;
      for (let i = 0; i < data.length; i++) {
        const excelObj = {}
        excelObj.序列号 = (i + 1).toString()
        excelObj.创建时间 = formatDate(data[i].createTime)
        excelObj.工人名称 = data[i].workerName
        excelObj.计划工作量 = data[i].number
        excelObj.实际工作量 = data[i].real_number
        excelObj.单位 = data[i].unitName
        excelObj.单价 = data[i].workerprice
        excelObj.实际收益 = data[i].actualIncome
        excelObj.客户单价 = data[i].customerprice
        excelObj.订单收入 = data[i].customerOutcome
        excelObj.订单号 = data[i].orderId
        excelObj.订单名称 = data[i].orderName
        excelObj.客户名称 = data[i].customerName
        excelObj.工序名称 = data[i].processName
        excelObj.订单状态 = data[i].orderState==1?'进行中':data[i].orderState==2?'已完成':data[i].orderState==3?'已回款':'已发工资'
        excelObj.完成时间 = formatDate(data[i].finishTime)
        excelData.push(excelObj)
      }
      console.log(excelData)
      if(excelData.length==0){
        this.loading = false;
        this.$message.error("暂无数据导出！");
      }else{
        this.$message.success("导出成功！");
        exportToExcel(fileName, excelData)
        this.loading = false;
      }
      
	  },
  }
}
</script>
<style scoped lang="scss">
::v-deep .el-card__header{
    padding: 0;
}
.top .el-form-item{
  margin-bottom: 0;
}
.boxs {
  padding: 20px;
}
.flex-box{
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.color-title{
  margin-bottom: 10px;
  color: #000;
}
</style>
